import { createRouter, createWebHashHistory } from 'vue-router'
import index from '../views/index'
import login from '../views/login'
import register from '../views/register'
import city from '../views/city'
import { isLogged } from '@/api'

const routes = [
  {path:'/index',redirect:"/"},
  {
    path: '/',
    name: 'index',
    component: index,
    meta: {
      islogin: false,
    }
  },
  {
    path: '/city',
    name: 'city',
    component: city,
    meta: {
      islogin: true,
    }
  },

  {
    path: '/login',
    name: 'login',
    component: login,
    meta: {
      islogin: false,
    }
  },

  {
    path: '/register',
    name: 'register',
    component: register,
    meta: {
      islogin: false,
    }
  },

]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next)=>{
  if(to.meta.islogin)
  {
    // 判断用户是否已经登录
    if(window.localStorage.token)
    {
      const token = window.localStorage.token
      isLogged(token)
      .then(success=>{
          if(success.status === 0)
          {
            next()
          }else{
            alert("请登陆后查看")
            next('/login')
          }
      })
      .catch(err=>{
        alert("请登陆后查看")
        next('/login')
      })
    }else{
      alert("请登陆后查看")
      next('/login')
    }

  }else{
    next()
  }
})


export default router
